var http = require('http')
var https = require('https')
var errorLogger = require("pomelo-logger").getLogger("error-log");
var WXBizDataCrypt = require('./WXBizDataCrypt')
var uuid = require("uuid")
var sha1 = require("./sha1.js")
module.exports = {}
var access_token = ""
var jsapi_ticket = {}
var appidList = {
  "wx2adc58d7c87a3b88" : "efcc58d0fe5c3f55de2938d17de7c64f"
}
// "wx2adc58d7c87a3b88" : "efcc58d0fe5c3f55de2938d17de7c64f"
for(var i in appidList){
  jsapi_ticket[i] = ""
}
var timer = false
var local = {}
var session_keyMap = {}
module.exports.h5Enter = function(code,appid,count,cb) {
    var string = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid
    +"&secret="+appidList[appid]+"&code="+code+"&grant_type=authorization_code"
    // var string = "http://pay.5d8d.com/H5Index/getAccessToken?code="+code
    var req=https.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          cb(data)
        })
    })
    req.on('error', function(e) {
      console.log("code换取token失败 : "+count+"  e: ")
      console.log(e)
      if(count > 3){
        cb(null,{"flag" : false,"err" : e})
        console.error(e);
      }else{
        module.exports.h5Enter(code,appid,++count,cb)
      }
    })
}
//微信客户端登录换取openid
module.exports.appEnter = function(code,appid,count,cb) {
  if(appidList[appid]){
    var myAppid = appid
    var MySecret = appidList[appid]
    var string = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+myAppid+"&secret="+MySecret+"&code="+code+"&grant_type=authorization_code"
    var req=https.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          if(data.errcode || data.errmsg || !data.openid || !data.session_key){
            console.log(data)
            cb(data)
          }else{
            session_keyMap[data.openid] = {
              session_key : data.session_key,
              appid : myAppid
            }
            cb(data)
          }
        })
    })
    req.on('error', function(e) {
      console.log("access_token code换取token失败 : "+count+"  e: ")
      console.log(e)
      if(count > 3){
        cb(e)
        console.error(e);
      }else{
        module.exports.appEnter(code,appid,++count,cb)
      }
    })
  }else{
    cb("appid error : "+appid)
  }
}
//微信小游戏使用临时登录凭证code 带appid 获取 session_key 和 openid
module.exports.miniEnter = function(code,appid,count,cb) {
  if(appidList[appid]){
    var myAppid = appid
    var MySecret = appidList[appid]
    var string = "https://api.weixin.qq.com/sns/jscode2session?appid="+myAppid+"&secret="+MySecret+"&js_code="+code+"&grant_type=authorization_code"
    var req=https.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          if(data.errcode || data.errmsg || !data.openid || !data.session_key){
            console.log(data)
            cb(data)
          }else{
            session_keyMap[data.openid] = {
              session_key : data.session_key,
              appid : myAppid
            }
            cb(data)
          }
        })
    })
    req.on('error', function(e) {
      console.log("miniEnter code换取token失败 : "+count+"  e: ")
      console.log(e)
      if(count > 3){
        cb(e)
        console.error(e);
      }else{
        module.exports.miniEnter(code,appid,++count,cb)
      }
    })
  }else{
    cb("appid error : "+appid)
  }
}
//微信小游戏登陆
module.exports.wxLogin = function(openid,session_key,encryptedData,iv) {
  if(session_keyMap[openid] && session_keyMap[openid].session_key === session_key){
    var myAppid = session_keyMap[openid].appid
    var pc = new WXBizDataCrypt(myAppid, session_key)
    var data = pc.decryptData(encryptedData,iv)
    if(!data || ! data.unionId){
      return openid
    }
    return data.unionId
  }else{
    return false
  }
}
//转接HTTPS接口
module.exports.getHttpsData = function(url,cb) {
  https.get(url,function(req,res){
      var responseText=[];
      var size = 0;
      req.on("data",function(chunk) {
        responseText.push(chunk);
        size+=chunk.length;
      })
      req.on("end",function() {
        responseText = Buffer.concat(responseText,size);
        var data = JSON.parse(responseText)
        cb(data)
      })
  })
}
//转接HTTP接口
module.exports.getHttpData = function(url,cb) {
  http.get(url,function(req,res){
      var responseText=[];
      var size = 0;
      req.on("data",function(chunk) {
        responseText.push(chunk);
        size+=chunk.length;
      })
      req.on("end",function() {
        responseText = Buffer.concat(responseText,size);
        var data = JSON.parse(responseText)
        cb(data)
      })
  })
}
//获取签名
module.exports.getSignature = function(appid,url,cb) {
  if(!jsapi_ticket[appid]){
    this.getTicket(appid,this.getSignature.bind(this,appid,url,cb))
    return
  }
  var timestamp = Math.floor(Date.now()/1000)
  var noncestr = uuid.v4()
  var string1 = "jsapi_ticket="+jsapi_ticket[appid]+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
  var signature = sha1(string1)
  cb({
    timestamp : timestamp,
    noncestr : noncestr,
    signature : signature
  })
}
//获取jsapi_ticket
module.exports.getTicket = function(appid,cb) {
  //jsapi_ticket存在直接返回，不存在则开启获取
  if(!appidList[appid]){
    console.log("appid不存在",appid)
    return
  }
  if(jsapi_ticket[appid]){
    cb(null,{flag : true,"jsapi_ticket" : jsapi_ticket[appid]})
  }else{
    local.getAccess_token(appid,cb)
    clearInterval(timer)
    timer = setInterval(local.getAccess_token.bind(null,appid),30 * 60 * 1000)
  }
}
local.getAccess_token = function(appid,cb) {
  var string = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appidList[appid]
  var req=https.get(string,function(res){
      var data = data
      res.on("data",function(chunk) {
        data += chunk
      })
      res.on("end",function() {
        data = data.replace("undefined","")
        data = JSON.parse(data)
        if(data.errcode || !data.access_token){
          errorLogger.info("获取微信token失败!")
          errorLogger.info(data.errmsg)
          access_token = ""
          if(cb){
            cb(null,{flag : false})
          }
          return
        }
        access_token = data.access_token
        local.getJsapi_ticket(appid,access_token,cb)
      })
  })
}
local.getJsapi_ticket = function(appid,token,cb){
    var string = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi"
    var req=https.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          if(data.errmsg !== "ok" || !data.ticket){
            errorLogger.info("获取微信ticket失败!")
            errorLogger.info(data.errmsg)
            jsapi_ticket[appid] = ""
            if(cb){
              cb(null,{flag : false})
            }
            return
          }
          jsapi_ticket[appid] = data.ticket
          // console.log("getJsapi_ticket",jsapi_ticket[appid])
          if(cb){
            cb(null,{flag : true,"jsapi_ticket" : jsapi_ticket[appid]})
          }
        })
    })
}
var getCity = function(ip,cb) {
    var string = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip
    var req=http.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          if(cb){
            cb(data)
          }
        })
    })
    req.on('error', function(e) {
      console.log("获取IP失败 : "+ip)
      cb({"area" : "","region" : "", "city" : ""})
      console.error(e);
    })
}